/*
    该模块用于实现用户请求的路由功能
    对于用户不同的请求，返回不同的响应
*/

#include <signal.h>

#include "../common/httplib.h"
#include "oj_control.hpp"

static oj_control::Control *control_ptr = nullptr;

void usage(const std::string &process)
{
    std::cout << "Usage: " << "\n\t" << process << " port" << std::endl;
}

// void recover(int)
// {
//     control_ptr->recoverMachine();
// }

// ./oj_server port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        usage(argv[0]);
        return 1;
    }

    // //当服务器收到SIGQUIT信号后，就会调用control，重新上线所有编译运行服务
    // signal(SIGQUIT, recover);

    uint16_t port = std::stoi(argv[1]);

    httplib::Server server;
    oj_control::Control control;
    control_ptr = &control;

    // 获取所有的题目列表
    server.Get("/all_questions", [&control](const httplib::Request &request, httplib::Response &response)
               {
                    std::string html;
                    control.allQuestions(html);
                    response.set_content(html, "text/html;charset=utf-8"); });

    // 获取指定题目
    //./question/100 —— 正则匹配
    server.Get(R"(/question/(\d+))", [&control](const httplib::Request &request, httplib::Response &response)
               { 
                std::string html;
                const std::string number = request.matches[1];
                control.question(number, html);
                response.set_content(html, "text/html;charset=utf-8"); });

    // 判断（编译 + 运行）指定题目
    server.Post(R"(/judge/(\d+))", [&control](const httplib::Request &request, httplib::Response &response)
                { 
                const std::string number = request.matches[1];
                std::string out_json;
                std::string in_json = request.body;
                bool ret = control.judge(number, in_json, out_json);
                if (ret == true)
                {
                    response.body = out_json;
                } });

    server.set_base_dir("./wwwroot");
    server.listen("0.0.0.0", port);

    return 0;
}